package org.light.simpleauth.verb;

import java.util.ArrayList;
import java.util.List;

import org.light.core.Verb;
import org.light.core.Writeable;
import org.light.domain.Domain;
import org.light.domain.JavascriptBlock;
import org.light.domain.JavascriptMethod;
import org.light.domain.Method;
import org.light.domain.Signature;
import org.light.domain.Statement;
import org.light.domain.StatementList;
import org.light.domain.Type;
import org.light.easyui.EasyUIPositions;
import org.light.exception.ValidateException;
import org.light.utils.StringUtil;
import org.light.utils.WriteableUtil;

public class ChangeMyPasswordUser extends Verb implements EasyUIPositions {
	
	@Override
	public Method generateDaoImplMethod() throws Exception {
		return null;
	}	

	@Override
	public Method generateDaoMethodDefinition() throws Exception {
		return null;
	}

	@Override
	public Method generateServiceMethodDefinition() throws Exception {
		return null;
	}

	@Override
	public Method generateServiceImplMethod() throws Exception  {
		return null;
	}
	
	public ChangeMyPasswordUser(Domain domain) throws ValidateException{
		super();
		this.domain = domain;
		this.dbType = domain.getDbType();
		this.setVerbName("ChangeMy"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+StringUtil.capFirst(this.domain.getStandardName()));
		this.setLabel("修改自己密码");
		if  (domain.getLanguage().equalsIgnoreCase("english"))  this.setLabel("Change My "+this.domain.findFieldByFixedName("password").getCapFirstFieldName());
	}

	@Override
	public Method generateControllerMethod() throws Exception {
		if (this.denied) return null;
		else {
			Method method = new Method();
			method.setStandardName("processRequest");
			method.setReturnType(new Type("void"));
			method.setThrowException(true);
			List<String> list = new ArrayList<String>();
			list.add("ServletException");
			list.add("IOException");
			method.setIsprotected(true);
			method.setOtherExceptions(list);
			method.addSignature(new Signature(1,"request",new Type("HttpServletRequest","javax.servlet.http")));
			method.addSignature(new Signature(2,"response",new Type("HttpServletResponse","javax.servlet.http")));
			method.addAdditionalImport("java.io.IOException");
			method.addAdditionalImport("java.io.PrintWriter");
			method.addAdditionalImport("javax.servlet.ServletException");
			method.addAdditionalImport("javax.servlet.http.HttpServlet");
			method.addAdditionalImport("javax.servlet.http.HttpServletRequest");
			method.addAdditionalImport("javax.servlet.http.HttpServletResponse");
			method.addAdditionalImport("java.util.Map");
			method.addAdditionalImport("java.util.TreeMap");
			method.addAdditionalImport("net.sf.json.JSONObject");
			method.addAdditionalImport("javax.servlet.http.HttpSession");
			method.addAdditionalImport(this.domain.getPackageToken()+"."+this.domain.getDomainSuffix()+"."+this.domain.getCapFirstDomainNameWithSuffix());
			method.addAdditionalImport(this.domain.getPackageToken()+".utils.PasswordUtil");
			method.addAdditionalImport(this.domain.getPackageToken()+".utils.StringUtil");
			method.addAdditionalImport(this.domain.getPackageToken()+"."+this.domain.getServiceSuffix()+"."+this.domain.getStandardName()+"Service");
			method.addAdditionalImport(this.domain.getPackageToken()+"."+this.domain.getServiceimplSuffix()+"."+this.domain.getStandardName()+"ServiceImpl");
			
			List<Writeable> sList = new ArrayList<Writeable>();
			long serial = 1000L;
			sList.add(new Statement(serial+1000L,0,"response.setContentType(\"application/json;charset=UTF-8\");"));
			sList.add(new Statement(serial+2000L,2,"Map<String,Object> result = new TreeMap<String,Object>();"));
			sList.add(new Statement(serial+3000L,2,"PrintWriter out = response.getWriter();"));
			sList.add(new Statement(serial+4000L,2,"try {"));
			sList.add(new Statement(serial+5000L,3,"HttpSession session = request.getSession();"));
			sList.add(new Statement(serial+6000L,4,this.domain.getCapFirstDomainNameWithSuffix()+" "+this.domain.getLowerFirstDomainName()+"0 = ("+this.domain.getCapFirstDomainNameWithSuffix()+")session.getAttribute(\"user\");"));
			sList.add(new Statement(serial+7000L,4,this.domain.getCapFirstDomainName()+"Service service = new "+this.domain.getCapFirstDomainName()+"ServiceImpl();"));
			sList.add(new Statement(serial+8000L,3,"String old"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+" = request.getParameter(\"old"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+"\");"));
			sList.add(new Statement(serial+9000L,3,"String new"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+" = request.getParameter(\""+this.domain.findFieldByFixedName("password").getLowerFirstFieldName()+"\");"));
			sList.add(new Statement(serial+10000L,3,""));
			sList.add(new Statement(serial+11000L,3,"if ("+this.domain.getLowerFirstDomainName()+"0!=null&&!StringUtil.isBlank("+this.domain.getLowerFirstDomainName()+"0.get"+this.domain.findFieldByFixedName("userName").getCapFirstFieldName()+"())) {"));
			FindUserShadow findShadow = new FindUserShadow(this.domain);
			sList.add(new Statement(serial+12000L,4,this.domain.getCapFirstDomainNameWithSuffix()+" db"+this.domain.getCapFirstDomainName()+" = service."+StringUtil.lowerFirst(findShadow.getVerbName())+"("+this.domain.getLowerFirstDomainName()+"0.get"+this.domain.findFieldByFixedName("userName").getCapFirstFieldName()+"());"));
			sList.add(new Statement(serial+13000L,4,"boolean _oldPasswordOk = PasswordUtil.verifyPassword(old"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+", db"+this.domain.getCapFirstDomainName()+".get"+this.domain.findFieldByFixedName("salt").getCapFirstFieldName()+"(), db"+this.domain.getCapFirstDomainName()+".get"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+"());"));
			sList.add(new Statement(serial+14000L,4,"if (_oldPasswordOk) {"));
			sList.add(new Statement(serial+15000L,5,"db"+this.domain.getCapFirstDomainName()+".set"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+"(new"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+");"));
			ChangePasswordUser changePass = new ChangePasswordUser(this.domain);
			sList.add(new Statement(serial+16000L,5,"service."+StringUtil.lowerFirst(changePass.getVerbName())+"(db"+this.domain.getCapFirstDomainName()+");"));
			sList.add(new Statement(serial+17000L,5,"result.put(\"success\",true);"));
			sList.add(new Statement(serial+18000L,5,"result.put(\"data\",null);"));
			sList.add(new Statement(serial+19000L,0,""));
			sList.add(new Statement(serial+20000L,5,"out.print(JSONObject.fromObject(result).toString());"));
			sList.add(new Statement(serial+21000L,5,"return;"));
			sList.add(new Statement(serial+22000L,4,"}"));
			sList.add(new Statement(serial+23000L,4,"result.put(\"success\",false);"));
			sList.add(new Statement(serial+24000L,4,"result.put(\"data\",null);"));
			sList.add(new Statement(serial+25000L,4,"out.print(JSONObject.fromObject(result).toString());"));
			sList.add(new Statement(serial+26000L,3,"}"));
			sList.add(new Statement(serial+27000L,1,"} catch (Exception e){"));
			sList.add(new Statement(serial+28000L,2,"e.printStackTrace();"));
			sList.add(new Statement(serial+29000L,2,"result.put(\"success\",false);"));
			sList.add(new Statement(serial+30000L,2,"result.put(\"reason\",e.getMessage());"));
			sList.add(new Statement(serial+31000L,2,"out.print(JSONObject.fromObject(result).toString());"));
			sList.add(new Statement(serial+32000L,1,"} finally {"));
			sList.add(new Statement(serial+33000L,2,"out.close();"));
			sList.add(new Statement(serial+34000L,1,"}"));	
			method.setMethodStatementList(WriteableUtil.merge(sList));
			return method;
		}
	}

	@Override
	public JavascriptBlock generateEasyUIJSButtonBlock() throws Exception {
		if (this.denied) return null;
		else {
			JavascriptBlock block = new JavascriptBlock();
			block.setSerial(100);
			block.setStandardName("changePassword"+domain.getCapFirstDomainName());
			StatementList sList = new StatementList();

			sList.add(new Statement(1000L,0,"{"));
			if ("english".equalsIgnoreCase(this.domain.getLanguage())) {
				sList.add(new Statement(2000L,1,"text:'Change Password',"));
			}else {
				sList.add(new Statement(2000L,1,"text:'设置密码',"));	
			}			
			sList.add(new Statement(3000L,1,"iconCls:'icon-reload',"));
			sList.add(new Statement(4000L,1,"handler:function(){"));
			sList.add(new Statement(5000L,2,"var rows = $(\"#dg\").datagrid(\"getChecked\");"));
			sList.add(new Statement(6000L,2,"if (rows == undefined || rows == null || rows.length == 0 ){"));
			if ("english".equalsIgnoreCase(this.domain.getLanguage())) {
				sList.add(new Statement(7000L,3,"$.messager.alert(\"Warning\",\"Please select one record.\",\"warning\");"));
			}else {
				sList.add(new Statement(7000L,3,"$.messager.alert(\"警告\",\"请选定一条记录！\",\"warning\");"));
			}
			sList.add(new Statement(8000L,3,"return;"));
			sList.add(new Statement(9000L,2,"}"));
			sList.add(new Statement(10000L,2,"if (rows.length > 1) {"));
			if ("english".equalsIgnoreCase(this.domain.getLanguage())) {
				sList.add(new Statement(11000L,3,"$.messager.alert(\"Warning\",\"Please select one record.\",\"warning\");"));
			}else {
				sList.add(new Statement(11000L,3,"$.messager.alert(\"警告\",\"请选定一条记录！\",\"warning\");"));
			}
			sList.add(new Statement(12000L,3,"return;"));
			sList.add(new Statement(13000L,2,"}"));
			sList.add(new Statement(14000L,2,"$(\"#ffchangePassword\").find(\"#"+this.domain.findFieldByFixedName("userName").getLowerFirstFieldName()+"\").val(rows[0][\""+this.domain.findFieldByFixedName("userName").getLowerFirstFieldName()+"\"]);"));
			sList.add(new Statement(15000L,2,"$('#wchangePassword').window('open');"));
			sList.add(new Statement(16000L,1,"}"));
			sList.add(new Statement(17000L,0,"}"));
			block.setMethodStatementList(sList);
			return block;			
		}
	}

	@Override
	public JavascriptMethod generateEasyUIJSActionMethod() throws Exception {
		if (this.denied) return null;
		else {
			Domain domain = this.domain;
			JavascriptMethod method = new JavascriptMethod();
			method.setSerial(200);
			method.setStandardName(StringUtil.lowerFirst(this.getVerbName()));			

			List<Writeable> sList = new ArrayList<Writeable>();

			sList.add(new Statement(1000L,1,"var "+this.domain.findFieldByFixedName("password").getLowerFirstFieldName()+" = $(\"#ffchangePassword\").find(\"#"+this.domain.findFieldByFixedName("password").getLowerFirstFieldName()+"\").val();"));
			sList.add(new Statement(2000L,1,"var old"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+" = $(\"#ffchangePassword\").find(\"#old"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+"\").val();"));
			sList.add(new Statement(3000L,1,"var confirm"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+" = $(\"#ffchangePassword\").find(\"#confirm"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+"\").val();"));
			sList.add(new Statement(4000L,1,"if (isBlank(old"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+")){"));
			if ("english".equalsIgnoreCase(this.domain.getLanguage())) {
				sList.add(new Statement(5000L,2,"$.messager.alert(\"Error\",\"Old password can not be empty.\",\"error\");"));
				sList.add(new Statement(6000L,2,"return;"));
				sList.add(new Statement(7000L,1,"}"));
				sList.add(new Statement(8000L,1,"if (isBlank("+this.domain.findFieldByFixedName("password").getLowerFirstFieldName()+")||isBlank(confirm"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+")){"));
				sList.add(new Statement(9000L,2,"$.messager.alert(\"Error\",\"New password can not be empty.\",\"error\");"));
				sList.add(new Statement(10000L,2,"return;"));
				sList.add(new Statement(11000L,1,"}"));
				sList.add(new Statement(12000L,1,"if (old"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+" == "+this.domain.findFieldByFixedName("password").getLowerFirstFieldName()+"){"));
				sList.add(new Statement(13000L,2,"$.messager.alert(\"Error\",\"New and old passwords can not be same.\",\"error\");"));
				sList.add(new Statement(14000L,2,"return;"));
				sList.add(new Statement(15000L,1,"}"));
				sList.add(new Statement(16000L,1,"if ("+this.domain.findFieldByFixedName("password").getLowerFirstFieldName()+"!=confirm"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+"){"));
				sList.add(new Statement(17000L,2,"$.messager.alert(\"Error\",\"New and confirm new password does not match.\",\"error\");"));
			} else {
				sList.add(new Statement(5000L,2,"$.messager.alert(\"错误\",\"旧密码不可为空！\",\"error\");"));
				sList.add(new Statement(6000L,2,"return;"));
				sList.add(new Statement(7000L,1,"}"));
				sList.add(new Statement(8000L,1,"if (isBlank("+this.domain.findFieldByFixedName("password").getLowerFirstFieldName()+")||isBlank(confirm"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+")){"));
				sList.add(new Statement(9000L,2,"$.messager.alert(\"错误\",\"新密码不可为空！\",\"error\");"));
				sList.add(new Statement(10000L,2,"return;"));
				sList.add(new Statement(11000L,1,"}"));
				sList.add(new Statement(12000L,1,"if (old"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+" == "+this.domain.findFieldByFixedName("password").getLowerFirstFieldName()+"){"));
				sList.add(new Statement(13000L,2,"$.messager.alert(\"错误\",\"新密码和旧密码不可相同！\",\"error\");"));
				sList.add(new Statement(14000L,2,"return;"));
				sList.add(new Statement(15000L,1,"}"));
				sList.add(new Statement(16000L,1,"if ("+this.domain.findFieldByFixedName("password").getLowerFirstFieldName()+"!=confirm"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+"){"));
				sList.add(new Statement(17000L,2,"$.messager.alert(\"错误\",\"新密码不匹配！\",\"error\");"));
			}
			sList.add(new Statement(18000L,2,"return;"));
			sList.add(new Statement(19000L,1,"}"));
			sList.add(new Statement(20000L,1,"$.ajax({"));
			sList.add(new Statement(21000L,2,"type: \"post\","));
			sList.add(new Statement(22000L,2,"url: \"../"+ this.domain.getControllerPackagePrefix()+"profile"+this.domain.getControllerNamingSuffix()+"/"+StringUtil.lowerFirst(this.getVerbName())+"\","));
			sList.add(new Statement(23000L,2,"data:  {"));
			sList.add(new Statement(24000L,3,this.domain.findFieldByFixedName("password").getLowerFirstFieldName()+":hex_sha1("+this.domain.findFieldByFixedName("password").getLowerFirstFieldName()+"),"));
			sList.add(new Statement(25000L,3,"old"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+":hex_sha1(old"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+"),"));
			sList.add(new Statement(26000L,2,"},"));
			sList.add(new Statement(27000L,2,"dataType: 'json',"));
			sList.add(new Statement(28000L,2,"success: function(data, textStatus) {"));
			sList.add(new Statement(29000L,3,"if (data.success) {"));
			sList.add(new Statement(30000L,4,"$(\"#wchangePassword\").window(\"close\");"));
			if ("english".equalsIgnoreCase(this.domain.getLanguage())) {
				sList.add(new Statement(31000L,4,"$.messager.alert(\"Success\",\"Successfully changed password.\",\"info\");"));
				sList.add(new Statement(32000L,3,"} else if (!data.success) {"));
				sList.add(new Statement(33000L,4,"$(\"#wchangePassword\").window(\"close\");"));
				sList.add(new Statement(34000L,4,"$.messager.alert(\"Failure\",\"Change password failed.\",\"error\");"));
			} else {
				sList.add(new Statement(31000L,4,"$.messager.alert(\"成功\",\"成功修改密码！\",\"info\");"));
				sList.add(new Statement(32000L,3,"} else if (!data.success) {"));
				sList.add(new Statement(33000L,4,"$(\"#wchangePassword\").window(\"close\");"));
				sList.add(new Statement(34000L,4,"$.messager.alert(\"失败\",\"修改密码失败！\",\"error\");"));
			}
			sList.add(new Statement(35000L,3,"}"));
			sList.add(new Statement(36000L,2,"},"));
			sList.add(new Statement(37000L,2,"complete : function(XMLHttpRequest, textStatus) {"));
			sList.add(new Statement(38000L,2,"},"));
			sList.add(new Statement(39000L,2,"error : function(XMLHttpRequest,textStatus,errorThrown) {"));
			sList.add(new Statement(40000L,3,"alert(\"Error:\"+textStatus);"));
			sList.add(new Statement(41000L,3,"alert(errorThrown.toString());"));
			sList.add(new Statement(42000L,2,"}"));
			sList.add(new Statement(43000L,1,"});"));

			method.setMethodStatementList(WriteableUtil.merge(sList));
			return method;	
		}
	}

	@Override
	public Method generateDummyDaoImplMethod() throws Exception {
		return null;
	}

	@Override
	public Method generateDummyServiceImplMethod() throws Exception {
		return null;
	}

	@Override
	public Method generateDummyDaoMethodDefinition() throws Exception {
		return null;
	}
}
